package com.shuwen.gcdj.service.strategyinspectionitemtemplate;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuwen.gcdj.bean.AddResp;
import com.shuwen.gcdj.bean.DictResp;
import com.shuwen.gcdj.bean.VoidResp;
import com.shuwen.gcdj.bean.inspectionitem.requset.*;
import com.shuwen.gcdj.bean.inspectionitem.response.InspectionItemPageResp;
import com.shuwen.gcdj.bean.inspectionitem.response.InspectionPageResp;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.exception.ApiException;
import com.shuwen.gcdj.common.util.BeanHelper;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.entity.StrategyInspectionitem;
import com.shuwen.gcdj.entity.StrategyInspectionitemtemplate;
import com.shuwen.gcdj.entity.StrategyInspectionitemtemplaterel;
import com.shuwen.gcdj.entity.SysDictionary;
import com.shuwen.gcdj.mapper.mysql.StrategyInspectionitemMapper;
import com.shuwen.gcdj.mapper.mysql.StrategyInspectionitemtemplateMapper;
import com.shuwen.gcdj.mapper.mysql.StrategyInspectionitemtemplaterelMapper;
import com.shuwen.gcdj.service.BaseService;
import com.shuwen.gcdj.service.strategyinspectionitem.StrategyInspectionitemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :yys
 * @date : 2023/5/12 10:45
 */
@Service
@Slf4j
public class StrategyInspectionitemtemplateService extends BaseService<StrategyInspectionitemtemplateMapper, StrategyInspectionitemtemplate> {


    @Autowired
    private StrategyInspectionitemtemplateMapper strategyInspectionitemtemplateMapper;

    @Autowired
    private StrategyInspectionitemtemplaterelMapper strategyInspectionitemtemplaterelMapper;

    @Autowired
    private StrategyInspectionitemService strategyInspectionitemService;

    @Autowired
    private StrategyInspectionitemMapper strategyInspectionitemMapper;

    /**
     * 获取检查项模板库分页信息
     * @param req
     * @return
     */
    public Page<InspectionItemPageResp> getThirdStructurePage(InspectionItemPageReq req) {
        Page<InspectionItemPageResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
        IPage<InspectionItemPageResp> allList = strategyInspectionitemtemplateMapper.getPage(page,req);
        List<InspectionItemPageResp> res = allList.getRecords();
        Page<InspectionItemPageResp> resPage = new Page<>(page.getCurrent(), page.getSize(), allList.getTotal());
        resPage.setRecords(res);
        return resPage;

    }

    /**
     * 添加检查项模板
     * @param initUser
     * @param req
     * @return
     */
    public AddResp addTemplate(InitUserDto initUser, AddTemplateReq req) {
        AddResp addResp = new AddResp();
//            添加模板
        StrategyInspectionitemtemplate strategyInspectionitemtemplate = new StrategyInspectionitemtemplate();
        strategyInspectionitemtemplate.setCreateId(initUser.getUserId());
        strategyInspectionitemtemplate.setUpdateId(initUser.getUserId());
        BeanUtil.copyProperties(req,strategyInspectionitemtemplate);
        int insert = strategyInspectionitemtemplateMapper.insert(strategyInspectionitemtemplate);
        if(insert < 1){
            throw new ApiException("添加失败");
        }
        addResp.setId(strategyInspectionitemtemplate.getId());

        if(!StringUtils.isEmpty(req.getTemplateId())){
//            启用已有模板
            LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StrategyInspectionitemtemplaterel::getTemplateId,req.getTemplateId())
                            .eq(StrategyInspectionitemtemplaterel::getStructureId, Constants.IS_TEMP + "")
                    .eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL);
            List<StrategyInspectionitemtemplaterel> list = strategyInspectionitemtemplaterelMapper.selectList(queryWrapper);
            for (StrategyInspectionitemtemplaterel s : list){
//            模板下增加检查项
                LambdaQueryWrapper<StrategyInspectionitem> queryWrapperOne = new LambdaQueryWrapper<>();
                queryWrapperOne.eq(StrategyInspectionitem::getId,s.getInspectionItemId())
                        .eq(StrategyInspectionitem::getIsDelete,Constants.IS_DELETE_NORMAL);
                StrategyInspectionitem strategyInspectionitem = strategyInspectionitemMapper.selectOne(queryWrapperOne);
                strategyInspectionitem.setId(null);
                strategyInspectionitem.setCreateId(initUser.getUserId());
                strategyInspectionitem.setUpdateId(initUser.getUserId());
                strategyInspectionitem.setUpdateTime(null);
                strategyInspectionitem.setCreateTime(null);
                strategyInspectionitemMapper.insert(strategyInspectionitem);
//                增加中间表
                s.setId(null);
                s.setCreateId(initUser.getUserId());
                s.setUpdateId(initUser.getUserId());
                s.setInspectionItemId(strategyInspectionitem.getId());
                s.setUpdateTime(null);
                s.setCreateTime(null);
                s.setTemplateId(strategyInspectionitemtemplate.getId());
                strategyInspectionitemtemplaterelMapper.insert(s);

            }

        }
        return addResp;
    }

    /**
     * 修改检查项模板状态
     * @param initUser
     * @param req
     * @return
     */
    public VoidResp edittemplatestate(InitUserDto initUser, CheckStateReq req) {
        StrategyInspectionitemtemplate byid = strategyInspectionitemtemplateMapper.selectById(req.getId());
        if(byid == null){
            throw new ApiException("数据不存在");
        }
        byid.setState(req.getState());
        byid.setUpdateId(initUser.getUserId());
        byid.setUpdateTime(null);
        strategyInspectionitemtemplateMapper.updateById(byid);
        return new VoidResp();
    }

    /**
     * 批量删除检查项模板
     * @param req
     * @return
     */
    public VoidResp batchTemplate(InitUserDto initUserDto,DeleteTemplateReq req) {
        for(String s : req.getIds()){
            StrategyInspectionitemtemplate byid = strategyInspectionitemtemplateMapper.selectById(s);
            if(byid == null){
                throw new ApiException("空数据"+s);
            }
//            获取检查项模板关联表信息
            LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StrategyInspectionitemtemplaterel::getTemplateId,s)
//                            .eq(StrategyInspectionitemtemplaterel::getStructureId,Constants.IS_TEMP + "")
                    .eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL);
            List<StrategyInspectionitemtemplaterel> sit = strategyInspectionitemtemplaterelMapper.selectList(queryWrapper);
            List<String> ids = new ArrayList<>();
            for(StrategyInspectionitemtemplaterel st : sit){
//                模板下的检查项id
                if(ids.contains(st.getInspectionItemId())){
                    continue;
                }
                ids.add(st.getInspectionItemId());
            }
            DeleteTemplateReq deleteTemplateReq = new DeleteTemplateReq();
            deleteTemplateReq.setIds(ids);
//            删除检查项关联表信息和检查项模板的检查项
            batchdeleteinspectionitem(initUserDto,deleteTemplateReq);
//            删除检查项模板
            byid.setIsDelete(Constants.IS_DELETE_YES);
            byid.setUpdateTime(null);
            byid.setUpdateId(initUserDto.getUserId());
            strategyInspectionitemtemplateMapper.updateById(byid);
        }
        return new VoidResp();
    }

    /**
     * 获取检查项列表分页信息
     * @param req
     * @return
     */
    public Page<InspectionPageResp> getinspectionitempagebytemplate(InspectionPageReq req) {
        Page<InspectionPageResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
        IPage<InspectionPageResp> allList = strategyInspectionitemtemplateMapper
                .getinspectionitempagebytemplate(page,req,Constants.STRATEGY_INSPECTIONITEM_RESULT,Constants.STRATEGY_INSPECTIONITEM_DISPOSAL_METHOD);
        List<InspectionPageResp> res = allList.getRecords();
        Page<InspectionPageResp> resPage = new Page<>(page.getCurrent(), page.getSize(), allList.getTotal());
        resPage.setRecords(res);
        return resPage;
    }

    /**
     * 批量新增检查项
     * @param initUser
     * @param req
     * @return
     */
    public List<AddResp> batchaddinspectionitem(InitUserDto initUser, BatchAddInspectionReq req) {
        if(req == null || CollectionUtils.isEmpty(req.getItems())){
            throw new ApiException("数据不能为空");
        }
        List<AddResp> addResps = new ArrayList<>();

        for (InspectionPamas inspectionPamas : req.getItems()){
            //        检查项表添加
            StrategyInspectionitem strategyInspectionitem = new StrategyInspectionitem();
            BeanUtil.copyProperties(inspectionPamas,strategyInspectionitem);
            strategyInspectionitem.setId(null);
            strategyInspectionitem.setUpdateId(initUser.getUserId());
            strategyInspectionitem.setCreateId(initUser.getUserId());
            strategyInspectionitemService.save(strategyInspectionitem);
            //            检查项模板关联表添加
            inspectionPamas.setId(null);
            StrategyInspectionitemtemplaterel strategyInspectionitemtemplate = new StrategyInspectionitemtemplaterel();
            BeanUtil.copyProperties(inspectionPamas,strategyInspectionitemtemplate);
            strategyInspectionitemtemplate.setUpdateId(initUser.getUserId());
            strategyInspectionitemtemplate.setCreateId(initUser.getUserId());
            strategyInspectionitemtemplate.setTemplateId(req.getTemplateId());
            strategyInspectionitemtemplate.setInspectionItemId(strategyInspectionitem.getId());
            strategyInspectionitemtemplaterelMapper.insert(strategyInspectionitemtemplate);
            AddResp addResp = new AddResp();
            addResp.setId(strategyInspectionitemtemplate.getId());
            addResps.add(addResp);
        }
        return addResps;
    }

    /**
     *批量删除检查项
     * @param initUser
     * @param req
     * @return
     */
    public VoidResp batchdeleteinspectionitem(InitUserDto initUser, DeleteTemplateReq req) {
        for(String s : req.getIds()){
            LambdaQueryWrapper<StrategyInspectionitem> queryWrapperOne = new LambdaQueryWrapper<>();
            queryWrapperOne.eq(StrategyInspectionitem::getIsDelete,Constants.IS_DELETE_NORMAL)
                    .eq(StrategyInspectionitem::getId,s);
            StrategyInspectionitem byId = strategyInspectionitemService.getOne(queryWrapperOne);
            if(byId == null){
                throw new ApiException("数据不存在");
            }
//            删除检查项模板关联表
            LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StrategyInspectionitemtemplaterel::getInspectionItemId,s)
//                    .eq(StrategyInspectionitemtemplaterel::getStructureId,Constants.IS_TEMP + "")
                    .eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL);
            List<StrategyInspectionitemtemplaterel> sit = strategyInspectionitemtemplaterelMapper.selectList(queryWrapper);
            for(StrategyInspectionitemtemplaterel st : sit){
                st.setIsDelete(Constants.IS_DELETE_YES);
                st.setUpdateTime(null);
                st.setUpdateId(initUser.getUserId());
                strategyInspectionitemtemplaterelMapper.updateById(st);
            }
//            删除检查项
            byId.setIsDelete(Constants.IS_DELETE_YES);
            byId.setUpdateTime(null);
            byId.setUpdateId(initUser.getUserId());
            strategyInspectionitemService.updateById(byId);
        }
        return new VoidResp();
    }

    /**
     * 编辑检查项
     * @param initUser
     * @param req
     * @return
     */
    public VoidResp editinspectionitem(InitUserDto initUser, InspectionPamas req) {
        if(req == null || StringUtils.isEmpty(req.getId())){
            throw new ApiException("id不能为空");
        }
        StrategyInspectionitem byId = strategyInspectionitemService.getById(req.getId());
        if(byId == null){
            throw new ApiException("检查项不存在");
        }
        BeanUtil.copyProperties(req,byId);
        byId.setUpdateTime(null);
        byId.setUpdateId(initUser.getUserId());
        strategyInspectionitemService.updateById(byId);
        return new VoidResp();
    }

    /**
     * 获取检查项列表信息
     * @param req
     * @return
     */
    public List<InspectionPageResp> getinspectionitembytemplate(InspectionPageReq req) {
       return strategyInspectionitemtemplateMapper
                .getinspectionitembytemplate(req,Constants.STRATEGY_INSPECTIONITEM_RESULT,Constants.STRATEGY_INSPECTIONITEM_DISPOSAL_METHOD);
    }

    public List<InspectionItemPageResp> getinspectionitemtamplate() {
        return strategyInspectionitemtemplateMapper.getinspectionitemtamplate();
    }

    public List<DictResp> getthirdstructurelist() {
        LambdaQueryWrapper<SysDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictionary::getParentCode,Constants.BASICS_STRUCTURE_THIRD_NAME)
                .eq(SysDictionary::getState,Constants.IS_ACTIVE_TEM)
                .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL);
        SysDictionary sysDictionary = new SysDictionary();
        List<SysDictionary> sysDictionaries = sysDictionary.selectList(queryWrapper);
        return BeanHelper.copyList(sysDictionaries, DictResp.class);
    }

    public List<DictResp> getinspectionitemtemplatelist() {
        LambdaQueryWrapper<StrategyInspectionitemtemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrategyInspectionitemtemplate::getState,Constants.IS_ACTIVE_TEM)
                .eq(StrategyInspectionitemtemplate::getIsDelete, Constants.IS_DELETE_NORMAL);
        StrategyInspectionitemtemplate inspectionitemtemplate = new StrategyInspectionitemtemplate();
        List<StrategyInspectionitemtemplate> sysDictionaries = inspectionitemtemplate.selectList(queryWrapper);
        List<DictResp> dictResps = new ArrayList<>();
        for(StrategyInspectionitemtemplate be : sysDictionaries){
            DictResp dictResp = new DictResp();
            dictResp.setName(be.getTemplateName());
            dictResp.setValue(be.getId());
            dictResps.add(dictResp);
        }
        return dictResps;
    }

    public List<DictResp> getinspectioniteminspectionresultlist() {
        LambdaQueryWrapper<SysDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictionary::getParentCode,Constants.STRATEGY_INSPECTION_ITEM_INSPECTION_RESULT)
                .eq(SysDictionary::getState,Constants.IS_ACTIVE_TEM)
                .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL);
        SysDictionary sysDictionary = new SysDictionary();
        List<SysDictionary> sysDictionaries = sysDictionary.selectList(queryWrapper);
        return BeanHelper.copyList(sysDictionaries, DictResp.class);
    }

    public List<DictResp> getinspectionitemdisposalmethodlist() {
        LambdaQueryWrapper<SysDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictionary::getParentCode,Constants.STRATEGY_INSPECTIONITEM_DISPOSAL_METHOD)
                .eq(SysDictionary::getState,Constants.IS_ACTIVE_TEM)
                .eq(SysDictionary::getIsDelete, Constants.IS_DELETE_NORMAL);
        SysDictionary sysDictionary = new SysDictionary();
        List<SysDictionary> sysDictionaries = sysDictionary.selectList(queryWrapper);
        return BeanHelper.copyList(sysDictionaries, DictResp.class);
    }
}
